from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.urls import reverse
from django.contrib import messages
from django.views.decorators.http import require_GET

from .forms import LoginForm, RegisterForm
from .utils import (
    generate_verification_code, 
    generate_verification_code_image, 
    save_verification_code_to_cache, 
    verify_code
)

def login_view(request):
    """登录视图"""
    if request.user.is_authenticated:
        return redirect('monitoring:dashboard')
    
    if request.method == 'POST':
        form = LoginForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                next_url = request.GET.get('next', reverse('monitoring:dashboard'))
                return redirect(next_url)
            else:
                messages.error(request, '用户名或密码错误')
    else:
        form = LoginForm()
    
    return render(request, 'accounts/login.html', {'form': form})

def register_view(request):
    """注册视图"""
    if request.user.is_authenticated:
        return redirect('monitoring:dashboard')
    
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            # 验证验证码
            user_code = form.cleaned_data.get('verification_code')
            if verify_code(request, user_code):
                user = form.save()
                login(request, user)
                messages.success(request, '注册成功')
                return redirect('monitoring:dashboard')
            else:
                messages.error(request, '验证码错误')
    else:
        form = RegisterForm()
    
    return render(request, 'accounts/register.html', {'form': form})

@login_required
def logout_view(request):
    """退出登录视图"""
    logout(request)
    return redirect('accounts:login')

@require_GET
def verification_code_view(request):
    """获取验证码图片"""
    code = generate_verification_code()
    image = generate_verification_code_image(code)
    save_verification_code_to_cache(request, code)
    return HttpResponse(image, content_type='image/png')
